<template>
  <el-select
    v-model="userIds"
    :multiple="multiple"
    :placeholder="placeholder"
    clearable
    filterable
    remote
    :remote-method="fetchUserList"
  >
    <el-option
      v-for="user in users"
      :key="user.id"
      :label="user.userNickName + '(' + user.userAccount + ')'"
      :value="user[valueKey]"
    />
  </el-select>
</template>
<script>
import { fetchUserPage } from '@/api/loginUser/common'

export default {
  name: 'UserSelect',
  emits: ['update:modelValue'],
  props: {
    modelValue: {
      type: [Number, String, Array],
    },
    multiple: {
      type: Boolean,
      default: () => {
        return false
      },
    },
    placeholder: {
      type: String,
      default: () => {
        return '请选择人员'
      },
    },
    valueKey: {
      type: String,
      default: () => {
        return 'id'
      },
    },
  },
  data() {
    return {
      users: [],
      fetchUserListTimeout: null,
    }
  },
  computed: {
    userIds: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      },
    },
  },
  watch: {
    userIds() {
      if (this.users.length == 0) {
        fetchUserPage({ userIds: this.userIds }).then((res) => {
          this.users = res.data.data.records
        })
      }
    },
  },
  methods: {
    fetchUserList(fuzzyUserInfo) {
      if (this.fetchUserListTimeout) {
        clearTimeout(this.fetchUserListTimeout)
      }

      let request = () => {
        fetchUserPage({ fuzzyUserInfo }).then((res) => {
          this.users = res.data.data.records
        })
      }

      this.fetchUserListTimeout = setTimeout(() => {
        request()
      }, 300)
    },
  },
}
</script>
